<?php
// +----------------------------------------------------------------------
// | Author: yaoyihong <510974211@qq.com>
// +----------------------------------------------------------------------
namespace addon\cms\logic;

use app\common\logic\LogicBase;
use \tpfcore\Core;
use \tpfcore\util\Config;
use think\Db;
use PDO;
/**
 *  逻辑
 */
class UserConsultManage extends LogicBase
{
	public function savePosts($data)
	{
		if(isset($data['tag_id']) && is_array($data['tag_id'])){
			$data['tag_id'] = implode(',',$data['tag_id']);
		}
        $validate=Core::addonValidate($this->name);
        $validate_result = $validate->scene('add')->check($data);
        if (!$validate_result) {
            return [RESULT_ERROR, $validate->getError(), null];
        }

		$last_id=Core::loadAddonModel($this->name)->saveObject($data);

		if(empty($data['id']) && !empty(config("config.cms_baidu")) && config("config.cms_baidu")['isauto_submit']==1){
			$submit_url_json = config("config.cms_baidu")['url'];
			$submit_url_json = str_replace('$id', $last_id, $submit_url_json);
			$arr = json_decode($submit_url_json,true);
			$submit_url[] = url($arr['url'],$arr['param']);
			$this->baidu_submit($submit_url);
		}

		if($last_id){
        	return [RESULT_SUCCESS, '操作成功', url('cms/Posts/index')];
        }
	}

	public function delPosts($data,$is_delete=false)
	{
		if(is_array($data['id'])){
			$data['id'] = ['in',implode(',',$data['id'])];//批量删除
		}
		return Core::loadAddonModel($this->name)->deleteObject($data,$is_delete,"isdelete")?[RESULT_SUCCESS, '删除成功', url('cms/Posts/index')]:[RESULT_ERROR, '删除失败', url('cms/Posts/index')];
	}

	public function getUserConsulList($_data)
	{
		$CustomForm = Core::loadAddonModel('CustomForm')->getOneObject(['id'=>$_data['form_id']]);
		if (empty($CustomForm)) {
			return [RESULT_ERROR, '没有对应的表单'];
		}

		$table = DB_PREFIX . strtolower($CustomForm->getData('table'));

		$model = Core::loadAddonModel('User')->alias('a');
		$model = $model->join([$table => 'b'], 'a.id = b.uid', 'right');

		$fields = array_column($CustomForm->fields, 'name');
		foreach ($fields as $key => $value) {
			$fields[$key] = 'b.' . $value;
		}
		$fields = array_merge($fields, ['b.id', 'b.uid', 'b.datetime','a.username', 'a.nickname', 'a.headimg', 'a.level']);

		$model = $model->field(implode(',', $fields))->where('uid', '>', 0);

		if (!empty($_data['keyword'])) {
			$model = $model->whereLike('a.username|a.nickname|a.mobile|b.username', "%{$_data['keyword']}%");
		}

		$list = $model->order('a.id desc')->paginate(10, false, ['query'=>request()->get()]);

		$MapUserLevel = [0=>'普通会员', 2=>'VIP会员', 3=>'老师'];
		foreach ($list as $key => $value) {
			foreach ($CustomForm->fields as $field) {
				if ($field['type'] == 'select_type') {
					$select_config = explode("\r\n", $field['exts']['select_config']);
					foreach ($select_config as $k => $v) {
						$temp_arr = explode("|", $v);
						if ($value->{$field['name']} == $temp_arr[1]) {
							$value->{$field['name']} = $temp_arr[0];
						}
					}
				}
			}
			$value->level_text = $MapUserLevel[$value->level];
		}

		return $list;
	}

	public function getUserConsulDetails($_data)
	{
		$CustomForm = Core::loadAddonModel('CustomForm')->getOneObject(['id'=>$_data['form_id']]);
		if (empty($CustomForm)) {
			return [RESULT_ERROR, '没有对应的表单'];
		}

		$table = DB_PREFIX . strtolower($CustomForm->getData('table'));

		$model = Core::loadAddonModel('User')->alias('a');
		$model = $model->join([$table => 'b'], 'a.id = b.uid', 'right');

		$fields = array_column($CustomForm->fields, 'name');
		foreach ($fields as $key => $value) {
			$fields[$key] = 'b.' . $value;
		}
		$fields = array_merge($fields, ['b.id', 'b.uid', 'b.datetime','a.username as user_name', 'a.nickname', 'a.headimg', 'a.level']);

		$Details = $model->field(implode(',', $fields))->where(['b.id'=>$_data['id']])->find();

		$MapUserLevel = [0=>'普通会员', 2=>'VIP会员', 3=>'老师'];
		$Details->level_text = $MapUserLevel[$Details->level];
		foreach ($CustomForm->fields as $field) {
			if ($field['type'] == 'select_type') {
				$select_config = explode("\r\n", $field['exts']['select_config']);
				foreach ($select_config as $k => $v) {
					$temp_arr = explode("|", $v);
					if ($Details->{$field['name']} == $temp_arr[1]) {
						$Details->{$field['name']} = $temp_arr[0];
					}
				}
			}
		}

		return [$CustomForm, $Details];
	}

	public function getCoUserInfo($uid)
	{
		$User = Core::loadAddonModel('User')->getOneObject(['id'=>$uid]);

		return $User;
	}

	public function saveCoUserData($_data)
	{
		if (empty($_data['id'])) {
			return [RESULT_ERROR, '用户ID不能为空'];
		}

		$result=Core::loadAddonModel('User')->saveObject($_data);
		if (false === $result) {
			return [RESULT_ERROR, '操作失败，请稍后再试！'];
		}

		return [RESULT_SUCCESS, '操作成功', url('cms/UserConsultManage/index', ['form_id'=>input('form_id')])];
	}

	/**
	 * 导出注册信息
	 * @param  [type] $_data [description]
	 * @return [type]        [description]
	 */
	public function exportUserConsul($_data)
	{
		$CustomForm = Core::loadAddonModel('CustomForm')->getOneObject(['id'=>$_data['form_id']]);
		if (empty($CustomForm)) {
			return [RESULT_ERROR, '没有对应的表单'];
		}

		$table = DB_PREFIX . strtolower($CustomForm->getData('table'));

		$model = Core::loadAddonModel('User')->alias('a');
		$model = $model->join([$table => 'b'], 'a.id = b.uid', 'right');

		$fields = array_column($CustomForm->fields, 'name');
		foreach ($fields as $key => $value) {
			$fields[$key] = 'b.' . $value;
		}
		$fields = array_merge($fields, ['b.id', 'b.uid', 'b.datetime','a.username', 'a.nickname', 'a.headimg', 'a.level']);

		$model = $model->field(implode(',', $fields))->where('uid', '>', 0);

		if (!empty($_data['keyword'])) {
			$model = $model->whereLike('a.username|a.nickname|a.mobile|b.username', "%{$_data['keyword']}%");
		}

		$list = $model->order('a.id desc')->select();

		$MapUserLevel = [0=>'普通会员', 2=>'VIP会员', 3=>'老师'];
		foreach ($list as $key => $value) {
			foreach ($CustomForm->fields as $field) {
				if ($field['type'] == 'select_type') {
					$select_config = explode("\r\n", $field['exts']['select_config']);
					foreach ($select_config as $k => $v) {
						$temp_arr = explode("|", $v);
						if ($value->{$field['name']} == $temp_arr[1]) {
							$value->{$field['name']} = $temp_arr[0];
						}
					}
				}
			}
			$value->level_text = $MapUserLevel[$value->level];

			$list[$key] = $value->toArray();
		}

		$ExportFields = [
			'nickname' => '姓名',
			'phone' => '电话',
			'level_text' => '用户等级',
		];
		foreach ($CustomForm->fields as $field) {
			$ExportFields[$field['name']] = $field['title'];
		}

		spreadsheet_export('用户注册导出', $ExportFields, $list);
	}
}